import 'dart:async';

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_webview_plugin/flutter_webview_plugin.dart';
//如果遇到以下 url 直接执行回退页面
const CATCH_URLS = ['m.ctrip.com/','http://m.ctrip.com/html5/', 'm.ctrip.com/html5/', 'm.ctrip.com/html5','m.ctrip.com/html5/you/'];
class WebView extends StatefulWidget {
   String url;
  final String title;
  final String statusBarColor;
  final bool hideAppBar;
  final bool backForbid;
  WebView({this.backForbid = false, this.title, this.url, this.statusBarColor, this.hideAppBar});

  @override
  _WebViewState createState() => _WebViewState();
}
class _WebViewState extends State<WebView> {

  final flutterWebviewPlugin = new FlutterWebviewPlugin();
  bool exiting = false;
  StreamSubscription<String> _onUrlChang ;
  StreamSubscription<WebViewStateChanged> _onStateChang;
  StreamSubscription<WebViewHttpError> _onHttpError;
  @override
  void initState() {
    print(widget.url);
    // TODO: implement initState
    super.initState();
    flutterWebviewPlugin.close();
//    监听浏览器开启
    _onUrlChang = flutterWebviewPlugin.onUrlChanged.listen((String url){
        print(url);
    });
//    监听浏览器状态变化
    _onStateChang = flutterWebviewPlugin.onStateChanged.listen((state) {
      switch(state.type){
        case WebViewState.startLoad:{
            if (_isToMain(state.url) && !exiting) {
              if (widget.backForbid){
//                print('launch curr url ${widget.backForbid}');
                flutterWebviewPlugin.launch(state.url);
              }
            }else {
              Navigator.pop(context);
//              print('${_isToMain(state.url)  }${!exiting} 6666666666666');
              exiting = true;
            }
          break;
        }
        default:
          break;
      }
    });
    _onHttpError = flutterWebviewPlugin.onHttpError.listen((WebViewHttpError err){print(err);});
  }

  _isToMain(String url) {
    bool contain = true;
    for (final value in CATCH_URLS) {
//      print('${url} ${value} url');
//        url 存在吗 存在则调用 endsWith方法(判断当前字符串 结尾是否包含url) 包含则返回false
      if (url?.endsWith(value) ?? false) {
        contain = false;
        break;
      }
    }
    return contain;
  }
  @override
  void dispose() {
    _onUrlChang.cancel();
    _onStateChang.cancel();
    _onHttpError.cancel();
    flutterWebviewPlugin.dispose();
    // TODO: implement dispose
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    String backgroundColor = widget.statusBarColor??'ffffff';
//    print('${Color(int.parse('0xff'+backgroundColor))} backgroundColor');
//    print('${widget.statusBarColor} ${Color(int.parse('0xFF'+backgroundColor))} widget.statusBarColor');
    Color backButtonColor;
    if (backgroundColor != 'ffffff') {
      backButtonColor = Colors.lightBlue;
    }else {
      backButtonColor = Colors.black;
    }
    // TODO: implement build
    return Scaffold(
      body: Column(
        children:<Widget>[
          _appBar(Color(int.parse('0xff'+backgroundColor)),backButtonColor),
          Expanded(
            child: WebviewScaffold(
              url: widget.url,
              withZoom: true,
              withLocalStorage: true,
              hidden: true,
              initialChild: Center(
                child: Text('wait...'),
              ),
            ),
          )
        ]
      ),
    );
  }
  _appBar(Color backgroundColor,Color backButtonColor) {
//    print('${backgroundColor} ${widget.hideAppBar} backgroundColor2');

    if (widget.hideAppBar ?? false) {
      return  Container(
        color: backgroundColor,
        height: 23,
      );
    }else {
      return Container(
        padding: EdgeInsets.fromLTRB(0, 40, 0, 10),
        child: FractionallySizedBox(
          widthFactor: 1,
          child: Stack(
            children: <Widget>[
              GestureDetector(
                onTap: (){
                  Navigator.pop(context);
                },
                child: Container(
                  margin: EdgeInsets.only(left: 12),
                  child: Icon(Icons.close,color: backButtonColor,),
                ),
              ),
             Positioned(
               left:0 ,
               right: 0,
               child:  Center(
                 child: Text(widget.title??'',style: TextStyle(fontSize: 20,color: backButtonColor),),
               ),
             )
            ],
          ),
        ),
      );
    }
  }
}